import Vue from "vue";

let ifmWindow: Window;
let windowPromise: Promise<Window>;
function getIframeWindow() {
  if (ifmWindow) {
    return Promise.resolve(ifmWindow);
  } else if (windowPromise) {
    return windowPromise;
  } else {
    windowPromise = new Promise<Window>(resolve => {
      const resizeIfm = document.createElement("iframe");
      resizeIfm.setAttribute("seamless", "seamless");
      resizeIfm.style.cssText =
        "top:0;left:0;width:100%;position:absolute;z-index:-1;border:none;box-sizing:border-box;visibility:hidden;opacity:0;pointer-events:none";
      resizeIfm.onload = function () {
        ifmWindow = resizeIfm.contentWindow;
        resolve(ifmWindow);
      };
      document.body.appendChild(resizeIfm);
    });
    return windowPromise;
  }
}

Vue.mixin({
  async beforeMount() {
    const { resized } = this as any;
    if (resized) {
      const resizeWindow = await getIframeWindow();
      resizeWindow.addEventListener("resize", resized);
    }
  },
  mounted() {
    const { resized } = this as any;
    if (resized) {
      Vue.nextTick(() => {
        // 页面首次加载完毕后，自动执行一次
        resized();
      });
    }
  },
  async beforeDestroy() {
    const { resized } = this as any;
    if (resized) {
      const resizeWindow = await getIframeWindow();
      resizeWindow.removeEventListener("resize", resized);
    }
  },
});
